<?php

namespace app\api\controller;

use app\admin\model\Recruitto;
use app\common\controller\Api;
use app\common\validate\serial\Log;
use think\Db;
use EasyWeChat\Factory;
use think\Session;
use app\index\controller\Assistant;

/**
 * 活动领取
 */
class Activity extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
  
    protected $noNeedRight = ['*'];
    protected $model;
    protected $guess;

    public  $app = null;

    public  $config = [
        // 必要配置
        'app_id'             => 'wx1f8725eef4e232a4',
        'mch_id'             => '1502026301',
        'key'                => '7xuEuQHG1nyCihYc0NgU0QAuvQT4sHvt',   // API 密钥
        // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
        'cert_path'          => '../../extend/cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
        'key_path'           => '../../extend/cert/apiclient_key.pem',      // XXX: 绝对路径！！！！
        'notify_url'         => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它
    ];

    public function _initialize(){
        $this->app = Factory::payment($this->config);
        $this->model = new \app\admin\model\Activity;
         $this->Sourcemodel = new \app\admin\model\base\Source;
         $this->guess = new \app\admin\model\Guess();
    }
    public function schoolNotify(){
        $response = $this->app->handlePaidNotify(function($message, $fail){

            if ($message['result_code']=='SUCCESS'){
                $out_trade_no = $message['out_trade_no'];
                $redis = getRedis();
                $tempData = $redis->get('temp_'.$out_trade_no);
                if (!$tempData)return true;

                $data = json_decode($tempData,1);

                $ttl = $redis->ttl('dt_'.$data['volume_id'].'_'.$data['openid']);

                $redKeys='form_'.$data['volume_id'].'_'.$data['openid'];

                $data['pays']=3;//支付成功
                if ($redis->get($redKeys)){
                    return true;
                }
                $data['sum']=$message['total_fee']/100;
                $data['out_trade_no']=$out_trade_no;
                $redis->set('succ_'.$out_trade_no,json_encode($message,1));
                $redis->expire('succ_'.$out_trade_no,60*60*24*2);
                $redis->set($redKeys,json_encode($data));
                $redis->expire($redKeys,$ttl);
                $redis->lPush('form_data',$data['volume_id'].'||'.$data['openid']);

            }
            file_put_contents('./ccc.txt',print_r($message,1));

            return true;
        });
        $response->send(); // return $response;
    }
    public function notify()
    {
        $response = $this->app->handlePaidNotify(function($message, $fail){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $out_trade_no = $message['out_trade_no'];
            //修改字段
            $row = $this->model->get(['out_trade_no'=>$out_trade_no,'pay'=>0]);
            if (!$row) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                $row->pay = 1;
                $count =  $this->model->where('pay','=',1)->count();//统计支付人数
                //支付成功通知
                $post = [
                    'id'=>$count+1,
                    'name'=>$row->name,
                    'phone'=>$row->phone,
                    'address'=>$row->shen_text.$row->shi_text.$row->xian_text.$row->address,
                    'text'=>__($row->version_text),
                    'moban'=>'create',
                ];
                $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
            }
            $row->save(); // 保存订单
            return true; // 返回处理完成
        });
        $response->send(); // return $response;
    }

    public function pay()
    {

        $row = $this->model->get(9);
        print_r($row->shen_text);exit;

        $user = Session::get('wechat_user');
        $result = $this->app->order->unify([
            'body' => '《考前突破卷·数学》领取',
            'out_trade_no' => '20150806125346'.date('ymdhis'),
            'total_fee' => 6,
            'notify_url' => 'http://oa.fc62.com/api/Activity/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => 'ovS7ms11fzsyG5RI3ddxm57MjU7I',
        ]);
        $jssdk = $this->app->jssdk;
        $json = $jssdk->bridgeConfig($result['prepay_id']);
        echo "<pre>";
        print_r($json);exit;
    }

    public function guess()
    {
        $user = Session::get('wechat_user');
        $row = $this->request->request();
        $activity = new \app\admin\model\Guess();
        unset($row['s']);
        if($activity->where('phone','=',$row['phone'])->find()){
            $this->error('已经领取,不可重复领取。');
        }
        $row['out_trade_no'] = 'hdyj'.date('ymdhis').mt_rand(999, 9999);
        $row['openid'] = $user['id'];
        $row['url'] = $user['avatar'];
        $sum = 9 * 100;
        $row['amount'] = $sum;
        $result = $activity->allowField(true)->save($row);
        if ($result !== false) {
            $result = $this->app->order->unify([
                'body' => '《考前突破卷》领取纸质版',
                'out_trade_no' => $row['out_trade_no'],
                'total_fee' => $sum,
                'notify_url' => 'http://oa.fc62.com/api/Activity/guessNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $user['id'],
            ]);
            $jssdk = $this->app->jssdk;
            $json = $jssdk->bridgeConfig($result['prepay_id']);
            $this->success('添加成功',json_decode($json,true));
        } else {
            $this->error('添加失败');
        }
    }

    public function guessedit($ids = null)
    {
        $user = Session::get('wechat_user');
        $parme = $this->request->request();
        $row = $this->guess->get($ids);
        $row->name = $parme['name'];
        $row->phone = $parme['phone'];
        $row->shen = $parme['shen'];
        $row->shi = $parme['shi'];
        $row->xian = $parme['xian'];
        $row->address = $parme['address'];
        $row->type = $parme['type'];
        $row->subject = $parme['subject'];
        $row->address = $parme['address'];
        $sum = 9 * 100;
        $row->amount = $sum;
        //去支付
        $result = $this->app->order->unify([
            'body' => '《考前突破卷》领取纸质版',
            'out_trade_no' => $row->out_trade_no,
            'total_fee' => $sum,
            'notify_url' => 'http://oa.fc62.com/api/Activity/guessNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user['id'],
        ]);
        $jssdk = $this->app->jssdk;
        $json = $jssdk->bridgeConfig($result['prepay_id']);
        $row->save();
        unset($parme,$row);
        $this->success('添加成功',json_decode($json,true));

    }

    /**
     * 考前猜题卷支付回调
     */
    public function guessNotify()
    {
        $response = $this->app->handlePaidNotify(function($message, $fail){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $out_trade_no = $message['out_trade_no'];
            //修改字段
            $row = $this->guess->get(['out_trade_no'=>$out_trade_no,'status'=>1]);
            if (!$row) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                $row->status = 2;
                $count =  $this->guess->where('status','=',2)->count();//统计支付人数
                //支付成功通知
                $post = [
                    'id'=>$count+1,
                    'name'=>$row->name,
                    'phone'=>$row->phone,
                    'address'=>$row->shen_text.$row->shi_text.$row->xian_text.$row->address,
                    'text'=>$row->type,
                    'subject'=>$row->subject,
                    'moban'=>'guess',
                ];
                $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
            }
            $row->save(); // 保存订单
            return true; // 返回处理完成
        });
        $response->send(); // return $response;
    }

  	public function breaks()
    {
        $user = Session::get('wechat_user');
        $row = $this->request->request();
        $activity = new \app\common\model\Activity;
        $row['out_trade_no'] = 'hdyj'.date('ymdhis').mt_rand(999, 9999);
        unset($row['s']);
        if($activity->where('phone','=',$row['phone'])->where('pay','=',1)->find())
        {
            $this->error('已经领取,不可重复领取。');
        }
        $row['openid'] = $user['id'];
        $row['url'] = $user['avatar'];
        $sum = 7 * 100;
        $row['sum'] = $sum;
        $result = $activity->allowField(true)->save($row);
        if ($result !== false) {
            $result = $this->app->order->unify([
                'body' => '《考前突破卷·数学》领取',
                'out_trade_no' => $row['out_trade_no'],
                'total_fee' => $sum,
                'notify_url' => 'http://oa.fc62.com/api/Activity/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $user['id'],
            ]);
            $jssdk = $this->app->jssdk;
            $json = $jssdk->bridgeConfig($result['prepay_id']);
            $this->success('添加成功',json_decode($json,true));
        } else {
            $this->error('添加失败');
        }
    }


    public function tel($tel)
    {
        $Recruitto = new Recruitto;
        if($Recruitto->where('tel','=',$tel)->find())
        {
            $this->error('手机号码重复，不可重复添加。');
        }
        $this->success('可以添加。');
    }

    public function recruit()
    {
         $this->error('暂时停止招募');
        $row = $this->request->post();
        $Recruitto = new Recruitto;
        if($Recruitto->where('tel','=',$row['tel'])->find()){
            $this->error('手机号码重复，不可重复添加。');
        }
        // gzy add
        if(preg_match('/[\x{4e00}-\x{9fa5}]/u',$row['source']) > 0){
            $info_source = $this->Sourcemodel->where(['name'=>$row['source']])->find();
            if($info_source){
                $row['source'] = $info_source['id'];
            }else{
                $this->error('没有此来源名称:《'.$row['source'].'》请联系管理员');
            }
        }else{
            $info_source = $this->Sourcemodel->where(['id'=>$row['source']])->find();
            if(!$info_source) $this->error('没有此来源id:《'.$row['source'].'》 请联系管理员');
        }
        // gzy end
        $Recruitto = new Recruitto;

        $result = $Recruitto->allowField(true)->save($row);
        if ($result !== false) {
            $result = $Recruitto->get($Recruitto->getLastInsID());
            $count = $Recruitto->count();
            $post = [
                'id'=>$count,
                'name'=>$result->name,
                'tel'=>$result->tel,
                'city'=>$result->sheng_text.$result->shi_text.$result->xian_text,
                'address'=>$result->address,
                'info'=>__($result->info),
                'apply_1'=>__($result->apply_1),
                'apply_2'=>__($result->apply_2),
                'apply_3'=>__($result->apply_3),
                'weixin'=>__($result->weixin),
                'email'=>__($result->email),
                'source'=>$info_source['name'],
                'moban'=>'recruit',
            ];
            $response = \fast\Http::post('http://oa.fc62.com/index/Assistant/chant',$post);
            $this->sms($post['tel']);
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    public function sms($phone = 17607118143)
    {
        $client = new \SoapClient('http://api.sms.hsyid.com:8088/XDTWebService.asmx?wsdl');
        $aryPara = array(
            'user'=>'hdyjsys',
            'pwd'=>'hdyjsys323',
            'mobiles'=>$phone,
            'contents'=>"【宏达一甲】亲爱的宝爸宝妈，很高兴收到您的报名申请，我们会在48小时内添加您为好友向您详细介绍项目信息。如因特殊原因没有添加到您，请关注公众号——绘本课堂，回复【招募】，获取项目负责人的联系方式。"
        );
        $response = $client->SendMessage($aryPara);
    }


}
